package com.kehutong.auth.controller;

import com.kehutong.auth.entity.Account;
import com.kehutong.auth.enums.RegChannel;
import com.kehutong.auth.service.AccountService;
import com.kehutong.common.ExcelUtil;
import com.kehutong.common.entity.Root;
import com.kehutong.common.errcode.Result;
import com.kehutong.common.util.Token;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.orm.jdbc.Page;

import java.io.File;
import java.util.List;
import java.util.Objects;

/**
 * 账号控制器
 *
 * @author: liukunlong
 * @date: 2021-08-13 15:40
 */
@MvcAction
@ReqMapping("/admin/account")
public class AccountController {
    private static final Logger logger = LoggerFactory.getLogger(AccountController.class);

    @Inject
    private AccountService accountService;

    /**
     * 用户账号列表信息
     *
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @ReqMapping("/page")
    public Object page(Token token, JSONObject jsonObject) throws Exception {
        if (!Root.isRoot(token.getUuid())) {//超级管理员
            jsonObject.put("khtIds",token.getCompanyNo());
        }
        return accountService.page(jsonObject);
    }

    /**
     * 根据条件导出业主数据
     *
     * @param jsonObject 条件对象
     * @return 文件
     * @throws Exception 异常
     */
    @ReqMapping("/export")
    public Object exportData(JSONObject jsonObject, Token token) throws Exception {
        if (!Root.isRoot(token.getUuid())) {//超级管理员
            jsonObject.put("khtIds",token.getCompanyNo());
        }
        jsonObject.put("pageNo", 1);
        jsonObject.put("pageSize", Short.MAX_VALUE);
        Page<Account> page =accountService.page(jsonObject);
        File dataFile = exportDataFile(page.getList());
        return Result.download(dataFile);
    }


    private File exportDataFile(List<Account> residentList) throws Exception {
        Workbook wb = exportWorkBook(residentList);
        return ExcelUtil.writeXlsFile(wb, "用户列表", ".xls");
    }


    private Workbook exportWorkBook(List<Account> accountList) {

        // 生成模板文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建工具
        CreationHelper helper = wb.getCreationHelper();
        //单元格样式类
        CellStyle dateCellStyle = wb.createCellStyle();
        //设置单元格格式
        dateCellStyle.setDataFormat(helper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));

        Sheet sheet = wb.createSheet();
        Row headerRow = sheet.createRow(0);
        int headerCellNum = 0;
        String[] chargeUserInstrument = {"姓名", "手机号码", "注册渠道","关联项目","状态","添加时间"};
        for (String s : chargeUserInstrument) {
            Cell cell = headerRow.createCell(headerCellNum++);
            cell.setCellValue(s);
        }

        int cellNum = 0;
        for (int i = 0; i < accountList.size(); i++) {
            Account account = accountList.get(i);
            Row row = sheet.createRow(i + 1);
            cellNum = 0;
            row.createCell(cellNum++).setCellValue(account.getRealname());
            row.createCell(cellNum++).setCellValue(account.getMobile());
            RegChannel regChannel=account.getRegChannel();
            if(Objects.isNull(regChannel)){
                row.createCell(cellNum++).setCellValue(RegChannel.MINI_PROGRAM.getDesc());
            }else{
                row.createCell(cellNum++).setCellValue(account.getRegChannel().getDesc());
            }
            row.createCell(cellNum++).setCellValue(account.getCommunityName());
            row.createCell(cellNum++).setCellValue(account.getStatus().getDesc());

            Cell tmpCell = row.createCell(cellNum++);
            tmpCell.setCellStyle(dateCellStyle);
            tmpCell.setCellValue(account.getCreateTime());
        }

        // 自动列宽
        for (int i = 0; i < cellNum; i++) {
            if (i == 0) {
                // id列不调整
                continue;
            }
            // 自动列宽
            ExcelUtil.autoSizeColumn(sheet, i);
        }
        return wb;
    }
}
